

import 'package:reabamshengchan/src/reabam/operation/bean/base/rb_response.dart';
import 'package:reabamshengchan/src/reabam/operation/bean/kuaimai/km_base_response.dart';
import 'package:reabamshengchan/src/reabam/operation/rb_config.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';

import 'bean/api_download_db_file_url.dart';
import 'bean/api_upload_order_task.dart';
import 'bean/bean_goodtype.dart';
import 'bean/bean_paytype.dart';
import 'bean/bean_retry_order.dart';
import 'bean/check_app_update/Request_check_app_update.dart';
import 'bean/kuaimai/km_base_request.dart';
import 'bean/socket/Request_server_ip_list.dart';
import 'bean/socket/Request_update_serversocket.dart';

typedef void RBApiCallbackSucceed(Map<String,dynamic> responseMap,Map<String,dynamic> headers_response);//headers_response: Map<String, List<String>>
typedef RBApiCallbackSucceedT<T> = void Function(T response,Map<String,dynamic> responseMap,Map<String,dynamic> headers_response);//headers_response: Map<String, List<String>>

abstract class RBApi{

  static Map<String,dynamic>? _getHeaders(){
    return null;
  }

  static void requestApi_async(
      {
        required String url,
        required String requestJson,
        required RBApiCallbackSucceed succeed,
        required XHttpCallbackFailed failed,
      }
      ){

    XHttpUtils.request_async(
        url: url,
        headers: _getHeaders(),
        dataJson: requestJson,
        succeed: (String result,Map<String,dynamic> headers_response){
          RBBaseResponse response=RBBaseResponse.fromJson(XJsonUtils.json2Map(result));
          String? code = response.code;
          String? message = response.msg;
          dynamic ResultInt = response.ResultInt;
          String? ResultString = response.ResultString;

          if(response.code!=null){
            if(code=="200") {
              succeed(XJsonUtils.json2Map(result),headers_response);
            }else{
              failed(code??'-1',message??'request failed!');
            }

          }else{
            if(ResultInt!=null && '$ResultInt' == '0') {
              succeed(XJsonUtils.json2Map(result),headers_response);
            }else{
              failed('$ResultInt',ResultString??'request failed!');
            }
          }
        },
        failed:failed
    );

  }

  static Future<Map<String,dynamic>?> requestApi_sync(
      {
        required String url,
        required String requestJson,
      }
      ) async{

    String result=await XHttpUtils.request_sync(
        url: url,
        headers: _getHeaders(),
        dataJson: requestJson
    );

    if(XStringUtils.isEmpty(result)){
      return null;
    }

    RBBaseResponse response=RBBaseResponse.fromJson(XJsonUtils.json2Map(result));
    String? code = response.code;
    String? message = response.msg;
    dynamic ResultInt = response.ResultInt;
    String? ResultString = response.ResultString;

    if(response.code!=null){
      if(code=="200") {
        return XJsonUtils.json2Map(result);
      }else{
        return null;
      }
    }else{
      if(ResultInt!=null && '$ResultInt'== '0') {
        return XJsonUtils.json2Map(result);
      }else{
        return null;
      }
    }
  }

  //快麦处理
  static void requestApi_km(
      {
        required String url,
        required String requestJson,
        required RBApiCallbackSucceed succeed,
        required XHttpCallbackFailed failed,
      }
      ){

    XHttpUtils.request_async(
        url: url,
        headers: _getHeaders(),
        dataJson: requestJson,
        succeed: (String result,Map<String,dynamic> headers_response){
          BaseKMResponse response=BaseKMResponse.fromJson(XJsonUtils.json2Map(result));
          bool status = response.status;
          String? message = response.message;
          if(status) {
            succeed(XJsonUtils.json2Map(result),headers_response);
          }else{
            failed('-1',message??'request failed!');
          }
        },
        failed:failed
    );

  }

  static String getXServerUrl(){
    return XSharePreferencesUtils.getString(RBConfigs.SP_serverAddress);
  }
  static String getXServerUrl2(){
    return XSharePreferencesUtils.getString(RBConfigs.SP_zuulServerAddress);
  }

  ////////////////////////////////////////////////////////////

  //检查版本升级
  static void checkAppVersionUpdate(
      {
        required String appCode,
        required RBApiCallbackSucceedT<ResponseCheckAppUpdate> succeed,
        required XHttpCallbackFailed failed,
      }
      ){
    //
    String url = "${getXServerUrl2()}/om/app/checkAppVersion";
    //
    RequestCheckAppUpdate request=RequestCheckAppUpdate(appCode,RBConfigs.version);
    //
    requestApi_async(
        url:url,
        requestJson:XJsonUtils.obj2Json(request),
        failed:failed,
        succeed: (Map<String,dynamic> responseMap,Map<String,dynamic> headers_response){
          ResponseCheckAppUpdate response=ResponseCheckAppUpdate.fromJson(responseMap);
          succeed(response,responseMap,headers_response);
        }
    );

  }


  //商品分类
  static void goodTypeList(
      {
        required String optType,
        required String filterType,
        required RBApiCallbackSucceedT<GoodTypeResponse> succeed,
        required XHttpCallbackFailed failed,
      }
      ){
    //
    String url = "${getXServerUrl()}/app/Business/Order/ProductTypes";
    //
    GoodTypeRequest request=GoodTypeRequest(optType:optType,filterType:filterType);
    //
    requestApi_async(
        url:url,
        requestJson:XJsonUtils.obj2Json(request),
        failed:failed,
        succeed: (Map<String,dynamic> responseMap,Map<String,dynamic> headers_response){
          GoodTypeResponse response=GoodTypeResponse.fromJson(responseMap);
          succeed(response,responseMap,headers_response);
        }
    );

  }

  //支付方式
  static void payList(
      {
        String? equipmentIdentity,
        required RBApiCallbackSucceedT<PayTypeResponse> succeed,
        required XHttpCallbackFailed failed,
      }
      ){
    //
    String url = "${getXServerUrl()}/app/Common/AppCode/PayType";
    //
    PayTypeRequest request=PayTypeRequest(equipmentIdentity:equipmentIdentity);
    //
    requestApi_async(
        url:url,
        requestJson:XJsonUtils.obj2Json(request),
        failed:failed,
        succeed: (Map<String,dynamic> responseMap,Map<String,dynamic> headers_response){
          PayTypeResponse response=PayTypeResponse.fromJson(responseMap);
          succeed(response,responseMap,headers_response);
        }
    );

  }

  //刷新订单是否已追平接口
  static Future<Response_retry_pos_order?> retryPosOrder(
      {
        required List<String> fastOrderNos,
        required String groupId,
      }
      ) async{
    //
    String url = "${getXServerUrl2()}/retail-order-front/fast/order/task/push/retry/batch/pos";
    //
    Request_retry_pos_order request=Request_retry_pos_order();
    request.fastOrderNos=fastOrderNos;
    request.groupId=groupId;
    //
    Map<String,dynamic>? responseMap= await requestApi_sync(
        url:url,
        requestJson:XJsonUtils.obj2Json(request)
    );

    if(responseMap!=null){
      Response_retry_pos_order response=Response_retry_pos_order.fromJson(responseMap);
      return response;
    }

    return null;

  }

  //检测订单是否已追平
  static Future<Response_check_order?> checkOrderBusinessStatus(
      {
        required List<String> fastOrderNos,
      }
      ) async{
    //
    String url = "${getXServerUrl2()}/retail-order-front/fast/order/task/push/checker";
    //
    Request_retry_pos_order request=Request_retry_pos_order();
    request.fastOrderNos=fastOrderNos;
    //
    Map<String,dynamic>? responseMap= await requestApi_sync(
        url:url,
        requestJson:XJsonUtils.obj2Json(request)
    );

    if(responseMap!=null){
      Response_check_order response=Response_check_order.fromJson(responseMap);
      return response;
    }

    return null;

  }

  //检测订单是否已追平
  static Future<Response_upload_order?> uploadOrderTask(
      {
         String? taskId,
         String? typeCode,
         String? fastOrderNo,
         String? pushJson,
         String? pushVersion,
         String? pushClient
      }
      ) async{
    //
    String url = "${getXServerUrl2()}/retail-order-front/fast/order/task/push";
    //
    Request_upload_order request=Request_upload_order(
        taskId: taskId,
        typeCode: typeCode,
        fastOrderNo: fastOrderNo,
        pushJson: pushJson,
        pushVersion: pushVersion,
        pushClient: pushClient
    );
    //
    Map<String,dynamic>? responseMap= await requestApi_sync(
        url:url,
        requestJson:XJsonUtils.obj2Json(request)
    );

    if(responseMap!=null){
      Response_upload_order response=Response_upload_order.fromJson(responseMap);
      return response;
    }

    return null;

  }


  static void downloadDBFileWaitH5CallbackFileUrl(
      {
        required RBApiCallbackSucceedT<RBBaseResponse> succeed,
        required XHttpCallbackFailed failed,
      }
      ){
    //
    String url = "${getXServerUrl2()}/product-task/offlinePos/downloadOfflineProducts";
    //
    RequestDownloadDbFileUrl request=RequestDownloadDbFileUrl();
    //
    requestApi_async(
        url:url,
        requestJson:XJsonUtils.obj2Json(request),
        failed:failed,
        succeed: (Map<String,dynamic> responseMap,Map<String,dynamic> headers_response){
          RBBaseResponse response=RBBaseResponse.fromJson(responseMap);
          succeed(response,responseMap,headers_response);
        }
    );

  }


  //上传更新serverSocket ip
  static void updateServerSocketInfo(
      {
        required List<BeanSocketPrintSetDTOS> printSetDTOS,
        required RBApiCallbackSucceedT<RBBaseResponse> succeed,
        required XHttpCallbackFailed failed,
      }
      ){
    //
    String url = "${getXServerUrl2()}/retail-order-front/printSet/save";
    //
    RequestUpdateServerSocket request=RequestUpdateServerSocket(printSetDTOS);
    //
    requestApi_async(
        url:url,
        requestJson:XJsonUtils.obj2Json(request),
        failed:failed,
        succeed: (Map<String,dynamic> responseMap,Map<String,dynamic> headers_response){
          RBBaseResponse response=RBBaseResponse.fromJson(responseMap);
          succeed(response,responseMap,headers_response);
        }
    );

  }

  //获得serverSocket ip
  static void getServerIPList(
      {
        required RBApiCallbackSucceedT<ResponseGetServerIPList> succeed,
        required XHttpCallbackFailed failed,
      }
      ){
    //
    String url = "${getXServerUrl2()}/retail-order-front/printSet/info";
    //
    RequestGetServerIPList request=RequestGetServerIPList(XSharePreferencesUtils.getString(RBConfigs.SP_companyId));
    //
    requestApi_async(
        url:url,
        requestJson:XJsonUtils.obj2Json(request),
        failed:failed,
        succeed: (Map<String,dynamic> responseMap,Map<String,dynamic> headers_response){
          ResponseGetServerIPList response=ResponseGetServerIPList.fromJson(responseMap);
          succeed(response,responseMap,headers_response);

        }
    );

  }


  //快麦打印//////////////////////////////////////////////////////////////////////////

  //测试域名
  //String _kmUrl="http://label-component-test.kuaimai.com";
  //正式域名
  static String _kmUrl="http://label-component.kuaimai.com";

  static String _kmAppId="1625638525787";
  static String _kmAppSecret="dabef9624c4d4a318cd9843584c2ef1c";

  //快麦api签名
  static void _setKuaimaiSign(BaseKMRequest request) {
    String timestamp = XDateUtils.getCurrentTime_String(format: XDateUtils.formatTimeDefault2);
    String randomNum = '${XNumberUtils.randomInt(12345678) + 200000000}';
    String x = '$_kmAppSecret$_kmAppId$timestamp$randomNum$_kmAppSecret';
    String sign = XJiamiUtils.strToMd5(x).toLowerCase();
    request.appId = _kmAppId;
    request.timestamp = timestamp;
    request.randomNum = randomNum;
    request.sign = sign;
  }

  //小票打印命令获取
  static void kmXiaopiaoPrint(
      {
        required String templateId,
        required String renderData,
        required String requestId,
        required RBApiCallbackSucceedT<Response_km_xiaopiao> succeed,
        required XHttpCallbackFailed failed
      }
      ) {

    //
    String url = "$_kmUrl/api/label/component/getEscInstruct";
    //
    Request_km_xiaopiao request = Request_km_xiaopiao(
        templateId: templateId,
        renderData: renderData,
        requestId: requestId
    );
    _setKuaimaiSign(request);

    //
    requestApi_km(
        url:url,
        requestJson:XJsonUtils.obj2Json(request),
        failed:failed,
        succeed: (Map<String,dynamic> responseMap,Map<String,dynamic> headers_response){
          Response_km_xiaopiao response=Response_km_xiaopiao.fromJson(responseMap);
          if(response.status){
            succeed(response,responseMap,headers_response);
          }else{
            failed('-1',response.message??'status=false');
          }
        }
    );

  }

  //tspl标签打印
  static void kmTSPLPrint(
      {
        required String templateId,
        required String renderData,
        required String requestId,
        required RBApiCallbackSucceedT<Response_km_xiaopiao> succeed,
        required XHttpCallbackFailed failed
      }
      ) {

    //
    String url = "$_kmUrl/api/label/component/getTsplInstruct";
    //
    Request_km_biaoqian request = Request_km_biaoqian(
      templateId: templateId,
      renderData: renderData,
      requestId: requestId,
    );
    _setKuaimaiSign(request);

    //
    requestApi_km(
        url:url,
        requestJson:XJsonUtils.obj2Json(request),
        failed:failed,
        succeed: (Map<String,dynamic> responseMap,Map<String,dynamic> headers_response){
          Response_km_xiaopiao response=Response_km_xiaopiao.fromJson(responseMap);
          if(response.status){
            succeed(response,responseMap,headers_response);
          }else{
            failed('-1',response.message??'status=false');
          }
        }
    );

  }

// public void kmXiaopiaoPrintPreview(Context context,
//     String templateId,
//     String renderData,
//     String requestId,
//     final XResponseListener2<Response_km_xiaopiaoPreview> listener) {
//
//   String url = kmUrl + "/api/label/component/getEscInstructImage";
//
//   Request_km_xiaopiao request = new Request_km_xiaopiao();
//   setKuaimaiSign(request);
//
//   request.templateId = templateId;
//   request.renderData = renderData;
//   request.requestId = requestId;
//
//   requestJsonByOkHttpPost_km(
//       context,
//       api.getAndroid_UUID(),
//       url,
//       request,
//       new HandlerResponse_CallBack_km<Response_km_xiaopiaoPreview>(context, Response_km_xiaopiaoPreview.class) {
//   @Override
//   public void failed(String s, String s1) {
//   listener.failed(s, s1);
//   }
//
//   @Override
//   public void succeed(Response_km_xiaopiaoPreview response, Map<String, String> headerMap) {
//   listener.succeed(response, headerMap);
//   }
//   });
// }

}